<template>
  <el-form ref="ruleFormRef" :rules="rules" :model="formConfig.dataObj" class="fixed-label-width">
    <el-form-item label="菜品名称" prop="foodName">
      <el-input v-model="formConfig.dataObj.foodName" />
    </el-form-item>
    <el-form-item label="图片" prop="foodImage">
      <upload ref="uploadRef" :imageUrl="formConfig.dataObj.foodImage"/>
    </el-form-item>
    <el-form-item label="店铺" prop="storeId">
      <el-select v-model="formConfig.dataObj.storeId" placeholder="店铺" filterable @change="changeStore">
        <el-option v-for="item in storeList" :key="item.storeId" :label="item.storeName" :value="item.storeId" />
      </el-select>
    </el-form-item>
    <el-form-item label="类别" prop="foodTypeName">
      <el-select v-model="formConfig.dataObj.foodTypeName" placeholder="类别" filterable>
        <el-option v-for="item in foodTypeOptions" :key="item.name" :label="item.name" :value="item.name" />
      </el-select>
    </el-form-item>
    <el-form-item label="合作价格" prop="storePrice">
      <el-input v-model="formConfig.dataObj.storePrice" type="number" />
      <span style="margin-left: 10px; color: #888">(元 / 份)</span>
    </el-form-item>
    <el-form-item label="排序" prop="sort">
      <el-input v-model="formConfig.dataObj.sort" @input="(v)=>(formConfig.dataObj.sort=v.replace(/[^\d.]/g,''))" />
    </el-form-item>
    <el-form-item label="菜品描述" prop="description">
      <el-input v-model="formConfig.dataObj.description" />
    </el-form-item>
    <el-form-item label="状态" prop="state">
      <el-switch v-model="formConfig.dataObj.stateFlag" inline-prompt size="large"
        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-text="上架" inactive-text="下架" />
    </el-form-item>
    <el-form-item label="是否必选" prop="required">
      <el-switch v-model="formConfig.dataObj.required" inline-prompt size="large" active-text="必选" inactive-text="非必选"
        style="--el-switch-off-color: #888" />
    </el-form-item>
    <el-form-item label="菜品规格" prop="description">
      <hz-button v-if="specification.length == 0" type="success" plain @click="clickAddFirstLeve1">新增</hz-button>
      <fdAddEditItem v-else :specification="specification" />
    </el-form-item>
  </el-form>

  <div class="dialog-footer my-dialog-foot">
    <hz-button type="primary" @click="clickSubmit">确定</hz-button>
    <hz-button @click="clickCancle">取消</hz-button>
  </div>
</template>
<script setup>
import { ref, reactive, watchEffect, getCurrentInstance } from "vue";
import { useStore } from "vuex";
import upload from '@/views/common/upload.vue'
import fdAddEditItem from './fdAddEditItem.vue'
import { ElMessage } from 'element-plus'

const store = useStore();
const { proxy } = getCurrentInstance();
const props = defineProps({
  formConfig: {
    default: {
      dataObj: {},
      dialog: {},
      type: '',
      okCallback: () => {},
      noCallback: () => {},
    }
  },
  storeList: {type: Array},
});

console.log(props.formConfig.dataObj)
props.formConfig.dataObj.stateFlag = props.formConfig.dataObj.state == 'yes';
const foodTypeOptions = ref([]);
const emits = defineEmits(["successCallback", 'cancleCallback']);
const ruleFormRef = ref(null);
const uploadRef = ref(null);

const specification = ref([])       // 规格数据

// 表单校验规则
const rules = reactive({
  foodName: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  storeId: [{ required: true, message: "店铺不能为空", trigger: "blur" }],
  foodTypeName: [{ required: true, message: "类别不能为空", trigger: "blur" }],
  storePrice: [{ required: true, message: "合作价格不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
});

initData();

/* ---------methods--------- */


// 初始赋值
function initData() {
  let dataObj = props.formConfig.dataObj
  let obj = props.storeList.find(val => val.storeId == dataObj.storeId)
  if (!obj && props.storeList[0]) {
    dataObj.storeId = props.storeList[0].storeId
  }
  if (dataObj.storeId) {
    getFoodTypeOptions(dataObj.storeId)
  }

  handleSpecification();
}

// 改变了店铺
function changeStore(val) {
  getFoodTypeOptions(val)
  let obj = props.storeList.find(val => val.storeId == val) || {};
  props.formConfig.dataObj.storeName = obj.storeName
  props.formConfig.dataObj.foodTypeName = '';
}

// 初始化规格数据
function handleSpecification() {
  let list = props.formConfig.dataObj.specification || [];
  list.forEach(item => {
    // 赋值规格数据传入规格组件来编辑
    specification.value.push(JSON.parse(JSON.stringify(item)))
  })

  if (props.formConfig.type == 'add') {
    clickAddFirstLeve1();
  }
}

// 添加第一个规格数据
function clickAddFirstLeve1() {
  specification.value.push({
    type: '一级规格',
    items: [
      { storePrice: 0, salePrice: 0, "name": "", "limitCount": 0 },
    ]
  })
}

// 获取要保存的数据
function getSubmitParam() {
  let params = { ...props.formConfig.dataObj}
  let {resultName, url} = uploadRef.value.image
  params.image = resultName ? resultName : url;   // resultNamez存在说明重新上传了图片
  params.state = params.stateFlag ? 'yes' : 'no';
  delete params.stateFlag;

  let _specification = [];
  // 筛选不为空的数据
  specification.value.forEach(val => {
    if (val.type) {
      let item = {
        type: val.type,
        items: []
      }
      val.items.forEach(i => {
        if (i.name && i.storePrice != null && i.salePrice != null && i.limitCount != null) {
          item.items.push(i);
        }
      })
      _specification.push(item);
    }
  })

  params.specification = _specification
  console.log(params)
  if (!params.image) {
    ElMessage.warning('请上传菜品图片')
    return
  }
  return params
}

// 获取菜品类别的下拉数据
function getFoodTypeOptions(storeId) {
  let params = { storeId }
  foodTypeOptions.value = [];
  proxy.$http.get('/jx/jxStoreManage/queryFoodTypeByStoreId', { params: params, successTip: false }).then(res => {
    if (res.code == 200) {
      res.result.forEach(val => {
        foodTypeOptions.value.push({ name: val, id: val })
      })
      
      if (foodTypeOptions.value.length) {
        if (props.formConfig.type == 'add' || !props.formConfig.dataObj.foodTypeName) {
          props.formConfig.dataObj.foodTypeName = foodTypeOptions.value[0].id
        }
      }
    }
  })
}


// 点击确定，提交数据
function clickSubmit() {
  if (!ruleFormRef.value) return
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      submitAdd();
    } else {
      console.log('提交校验不通过', fields)
    }
  })

}

// 提交新增\编辑，区别在于编辑时会多带foodId数据
function submitAdd() {
  let params = getSubmitParam();
  if (!params) {
    return;
  }
  proxy.$http.post('/jx/jxFoodManage/addOrEditFoodInfo', params, { successTip: true }).then(res => {
    if (res.code == 200) {
      props.formConfig.dialog.show = false;
      props.formConfig.okCallback();
    }
  })
}

// 点击取消的回调
function clickCancle() {
  props.formConfig.dialog.show = false;
}

// 对外暴露数据
defineExpose({});
</script>

<style lang="scss" scoped></style>
